################################################################################
#                                                                              #
#                        SCRIPT III - SQS AND SQUARES                          #
#                                                                              #
#                               Bethany J. Allen                               #
#                                                                              #
################################################################################
#This script is adapted from one distributed by Bethany J. Allen at PtogPal 2020. 
#These commands filter raw occurence data from PBDB and calculate Alroy's (2018) extrapolated squares.
#Please do not distribute without permission from Bethany J. Allen


#Load the requied packages 
PackageBundle <- c("devtools", "earth", "iNEXT", "metatree", "nlme", "paleoTS",
  "plotrix", "praise", "tidyverse", "velociraptr", "viridis")
for(pkg in c(PackageBundle, "metatree")) try(library(pkg,
  character.only = TRUE), silent = TRUE)

#load your occurrence data into R
RawData <-read.csv("glires.csv",
  header = TRUE, stringsAsFactors = FALSE)

  RawData <- RawData[, c("occurrence_no", "collection_no", "phylum", "class",
                       "order", "family", "genus", "accepted_name", "early_interval",
                       "late_interval", "max_ma", "min_ma", "lng", "lat", "paleolng",
                       "paleolat", "identified_rank", "formation")]

unique(RawData[, "identified_rank"])
RawData$genus <- as.character(RawData$genus)
RawData$formation <- as.character(RawData$formation)

RawData <- dplyr::filter(RawData, nchar(genus) > 0)

RawData <- dplyr::distinct(RawData, accepted_name, collection_no,
                           .keep_all = TRUE)

#specify the time interval your interested in and provide dates						   
StageNames <- c("Danian", "Selandian", "Thanetian", "Ypresian",
                "Lutetian", "Bartonian","Priabonian","Rupelian",
                "Chattian","Aquitanian","Burdigalian","Langhian",
                "Serravallian","Tortonian","Messinian","Zanclean",
                "Piacenzian","Gelasian","Calabrian","MiddlePleistocene",
                "UpperPleistocene","Greenlandian","Northgrippian","Meghalayan")
StageMidpoints <- c(63.8, 60.4, 57.6, 51.9, 44.5, 39.5, 35.85, 30.86, 25.425, 21.735, 18.205, 14.895, 12.725, 9.438,
                    6.2895, 4.4665, 3.09, 2.19, 1.2905, 0.4535, 0.06885, 0.009988, 0.006238, 0.0021)


# Squares uses rank abundance strings of each taxon (abundance is the number of PBDB collections the taxon is present in)

#Make an empty list to store the strings in
stage_freq2 <- list()

#Now loop through each stage
for (i in 1:length(StageNames)) {
  
  # Then filter the dataset to that stage and make a rank abundance string:
  f_list2 <- RawData %>% filter(early_interval == StageNames[i]) %>% count(., genus) %>%
    arrange(desc(n)) %>% select(n)
  
  # Now convert it to a vector
  f_list2 <- unlist(f_list2, use.names = F)
  
  #and add the vector to the list
  stage_freq2[[i]] <- f_list2
  
}

#Then rename the strings with their stages
names(stage_freq2) <- StageNames

#Alroy (2018) states the equation for extrapolating with squares, and here we have the equation hard-coded so you can see what is happening.

#You start by making an empty vector to store the squares estimates in
squares_list <- vector("numeric", length = 0)

#Then you loop through each stage
for(i in 1:length(stage_freq2)) {
  
  #This line filters the rank-abundance string of the stage of interest
  count_list <- stage_freq2[[i]]
  
  #Then you can find total numbers of genera in the string (by finding the length of the list)
  genus_count <- length(count_list)
  
  #Find the number of singletons (the number of genera in the string with an abundance of 1):
  sing_count <- sum(count_list == 1)
  
  #Find the number of individuals (the sum of the string):
  ind_count <- sum(count_list)
  
  #Find the sum of the string squared (this is where the name comes from)
  sum_nsq <- sum(count_list^2)
  
  #Now you have your input parameters, put them into our squares equation
  squares <- genus_count + (((sing_count^2)*sum_nsq)/((ind_count^2) - (sing_count*genus_count)))
  

  
  #Finally, add the squares estimate to the end of the vector
  squares_list <- append(squares_list, squares)
  
}

#You now have our list of diversity estimates per stage.
#
#Label the squares estimates with their stage midpoints...
to_plot <- data.frame(squares_list, StageMidpoints)

# ...and finally plot them. The grey lines to indicate the start and end of the stages
squares <- ggplot(to_plot, aes(x = StageMidpoints, y = squares_list)) +
  geom_line(size = 1) + geom_point() +
  scale_x_reverse(limits = c(70, 0)) + labs(x = "Ma", y = "Squares genus diversity") +
  geom_vline(aes(xintercept = 66), colour = "grey") + #Start of Paleocene
  geom_vline(aes(xintercept = 56), colour = "grey") + #Eocene
  geom_vline(aes(xintercept = 33.9), colour = "grey") + #Oligocene
  geom_vline(aes(xintercept = 23.03), colour = "grey") + #Miocene
  geom_vline(aes(xintercept = 5.333), colour = "grey") + #Pliocene
  geom_vline(aes(xintercept = 2.58), colour = "grey") + #Pleistocene
  theme_classic()
squares